package com.wang.mall.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Value("${no.require.uris:/product/product/getData,/users/member/login,/product/upload/image,/users/sys/login,/users/sys/captcha.jpg}")
    private Set<String> noRequireTokenUris;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、看该接口是否需要token才能访问
        if (!isRequestToken(exchange)) {
            return chain.filter(exchange); //不需要token直接放行
        }
        // 2、如果接口需要token，取出token
        String token = getUserToken(exchange);
        // 3、判断token是否有效
        if (StringUtils.isEmpty(token)) {
            // token为空
            return buildNoAuthorizationResult(exchange);
        }

        Boolean aBoolean = redisTemplate.hasKey(token);
        if (aBoolean != null && aBoolean) {
            // token有效直接放行
            return chain.filter(exchange);
        }
        return buildNoAuthorizationResult(exchange);
    }


    /**
     * 给予用户响应一个没有token的错误
     *
     * @param exchange
     * @return
     */
    private Mono<Void> buildNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type", "application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "NoAuthorization");
        jsonObject.put("errorMsg", "Token is Null or Error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }


    /**
     * xx
     * 判断给接口是否需要token访问
     *
     * @param exchange
     * @return
     */
    private boolean isRequestToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if (path.startsWith("/product/product/info/")) {
            return false;
        }
        if (noRequireTokenUris.contains(path)) {
            return false; //不需要token
        }
        return true;
    }

    /**
     * 获取当前用户的token
     *
     * @param webExchange
     * @return
     */
    public String getUserToken(ServerWebExchange webExchange) {
        String token = webExchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ", "");
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
